﻿angular.module('Caltech').controller('procedureController', function ($scope, Restangular, ngTableParams, $location, $stateParams) {
    'use strict';

    $scope.filters = {};

    $scope.paging = {
        index: 1,
        size: 10
    };

    $scope.filter = false;

    $scope.search = function (index) {
        if ($scope.tableParams) {
            $scope.tableParams.reload();
        } else {
            $scope.tableParams = new ngTableParams({
                page: $scope.paging.index,
                count: $scope.paging.size
            }, {
                counts: [15, 20, 25],
                getData: function ($defer, params) {
                    var name = $scope.filters.name || undefined;
                    if ($scope.filter) {
                        $scope.filter = false;
                        params.page(1);
                    }

                    Restangular.all('procedure')
                        .getList({
                            page: params.page(),
                            count: params.count(),
                            name: name || undefined
                        }).then(function (standards) {
                            params.total(standards.total);
                            $defer.resolve(standards);

                            $location.search('name', $scope.filters.name || undefined);

                            if (params.page() != $scope.paging.index) {
                                $location.search('pageIndex', params.page());
                                $scope.paging.index = params.page();
                            }
                            if (params.count() != $scope.paging.size) {
                                $location.search('pageIndex', 1);
                                $location.search('pageSize', params.count());
                                $scope.paging.size = params.count();
                            }

                        });
                }
            });
        }
    };

    $scope.reSearch = function () {
        $location.search('pageIndex', 1);
        $scope.paging.index = 1;
        $scope.filter = true;
        $scope.search();
    };

    if ($stateParams.pageIndex || $stateParams.name || $stateParams.pageSize) {
        $scope.filters.name = $stateParams.name;
        $scope.paging = {
            index: $stateParams.pageIndex || 1,
            size: $stateParams.pageSize || 10
        };
        $scope.search();
    } else {
        $scope.search();
    }
});